<?php


namespace app\privatearea\controller\v1;


use app\common\cachemodel\privatearea\PrivateAreaGoods;
use app\common\cachemodel\privatearea\PrivateAreaOrders;
use app\common\cachemodel\privatearea\PrivateAreaQuestionInfo;
use app\common\lib\AliOss;
use app\common\lib\Util;
use app\common\model\Recode;
use app\privatearea\controller\Auth;

class Question extends Auth
{
    /**
     * 提交问题信息
     */
    public function submitQuestionInfo()
    {
        $sn = input('sn/s', '');
        $id = input('id/d', 0);
        $rid1 = input('rid1/d', 0);
        $name1 = trim(input('name1/s', ''));
        $photo1 = input('photo1/s', '');
        $rid2 = input('rid2/d', 0);
        $name2 = trim(input('name2/s', ''));
        $photo2 = input('photo2/s', '');
        $supplementInfo = input('supplement_info/s', '');
        $cards = input('cards/s', '');
        $question = input('question/s', '');
        $divinationData = input('divination_data/s', '');

        if (!$sn)
        {
            return show(config('code.error'), '请求异常！咨询问题信息缺失～');
        }

        if ($rid1 && $rid2 && $rid1 === $rid2)
        {
            return show(config('code.error'), '请求异常！请稍后再试～');
        }

        $questionInfoModel = new PrivateAreaQuestionInfo();
        $goodModel = new PrivateAreaGoods();
        $goodInfo = $goodModel->getPrivateAreaGoodInfo($sn, ['uid', 'lid', 'type', 'price', 'name', 'extend', 'info_type', 'card_num', 'order_num', 'is_pay']);

        if ($this->user['id'] !== $goodInfo['uid'])
        {   // 非指定用户
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
        if ($goodInfo['order_num'])
        {
            if ($goodInfo['is_pay'])
            {
                return show(config('code.error'), '服务异常，请稍后再试～');
            } else
            {
                $orderStatus = (new PrivateAreaOrders())->getInfoById($goodInfo['order_num'], ['status']);
                if (!in_array((int)$orderStatus['status'], [3, 5], true))
                {
                    return show(config('code.error'), '服务异常，请稍后再试～');
                }
            }
        }

        $questionData = [
            'recode1' => null,
            'name1' => '',
            'photo1' => '',
            'recode2' => null,
            'name2' => '',
            'photo2' => '',
            'cards' => '',
            'question' => '',
            'divination_data' => ''
        ];
        if (in_array($goodInfo['type'], [1, 3, 4, 6], true))
        {   // 看盘   疗愈调频   面向
            if (in_array($goodInfo['info_type'], [1, 3, 4, 6, 7], true))
            {
                if (empty($rid1))
                {
                    return show(config('code.error'), '请求异常！档案信息缺失～');
                } else
                {
                    $recodeInfo1 = (new Recode())->getRecode(['id' => $rid1]);
                    if ($recodeInfo1['uid'] != $this->user['id'])
                    {
                        return show(config('code.error'), '请求异常！档案信息不存在～');
                    }
                    $questionData['recode1'] = [
                        'id' => $rid1,
                        'avatar' => $recodeInfo1['avatar'],
                        "name" => $recodeInfo1['name'],
                        "type" => (int)$recodeInfo1['type'],
                        "year" => (int)$recodeInfo1['year'],
                        "month" => (int)$recodeInfo1['month'],
                        "day" => (int)$recodeInfo1['day'],
                        "hour" => (int)$recodeInfo1['hour'],
                        "minute" => (int)$recodeInfo1['minute'],
                        "timezone" => (int)$recodeInfo1['timezone'],
                        "long_deg" => (int)$recodeInfo1['long_deg'],
                        "long_min" => (int)$recodeInfo1['long_min'],
                        "ew" => (int)$recodeInfo1['ew'],
                        "lat_deg" => (int)$recodeInfo1['lat_deg'],
                        "lat_min" => (int)$recodeInfo1['lat_min'],
                        "ns" => (int)$recodeInfo1['ns'],
                        "is_summer" => (int)$recodeInfo1['is_summer'],
                        "birth_country" => $recodeInfo1['birth_country'],
                        "birth_province" => $recodeInfo1['birth_province'],
                        "birth_city" => $recodeInfo1['birth_city'],
                        "live_country" => $recodeInfo1['live_country'],
                        "live_province" => $recodeInfo1['live_province'],
                        "live_city" => $recodeInfo1['live_city'],
                        "isself" => (int)$recodeInfo1['isself'],
                    ];
                }
            }
            if (in_array($goodInfo['info_type'], [2, 3, 5, 6, 8], true))
            {
                if (empty($name1))
                {
                    return show(config('code.error'), '请求异常！真实姓名不能为空～');
                } else
                {
                    $questionData['name1'] = $name1;
                }
                if (empty($photo1))
                {
                    return show(config('code.error'), '请求异常！照片信息缺失～');
                } else
                {
                    $questionData['photo1'] = $photo1;
                }
            }
            if (in_array($goodInfo['info_type'], [4, 6, 8], true))
            {
                if (empty($rid2))
                {
                    return show(config('code.error'), '请求异常！Ta的档案信息缺失～');
                } else
                {
                    $recodeInfo2 = (new Recode())->getRecode(['id' => $rid2]);
                    if ($recodeInfo2['uid'] != $this->user['id'])
                    {
                        return show(config('code.error'), '请求异常！Ta的档案信息不存在～');
                    }
                    $questionData['recode2'] = [
                        'id' => $rid2,
                        'avatar' => $recodeInfo2['avatar'],
                        "name" => $recodeInfo2['name'],
                        "type" => (int)$recodeInfo2['type'],
                        "year" => (int)$recodeInfo2['year'],
                        "month" => (int)$recodeInfo2['month'],
                        "day" => (int)$recodeInfo2['day'],
                        "hour" => (int)$recodeInfo2['hour'],
                        "minute" => (int)$recodeInfo2['minute'],
                        "timezone" => (int)$recodeInfo2['timezone'],
                        "long_deg" => (int)$recodeInfo2['long_deg'],
                        "long_min" => (int)$recodeInfo2['long_min'],
                        "ew" => (int)$recodeInfo2['ew'],
                        "lat_deg" => (int)$recodeInfo2['lat_deg'],
                        "lat_min" => (int)$recodeInfo2['lat_min'],
                        "ns" => (int)$recodeInfo2['ns'],
                        "is_summer" => (int)$recodeInfo2['is_summer'],
                        "birth_country" => $recodeInfo2['birth_country'],
                        "birth_province" => $recodeInfo2['birth_province'],
                        "birth_city" => $recodeInfo2['birth_city'],
                        "live_country" => $recodeInfo2['live_country'],
                        "live_province" => $recodeInfo2['live_province'],
                        "live_city" => $recodeInfo2['live_city'],
                        "isself" => (int)$recodeInfo2['isself'],
                    ];
                }
            }
            if (in_array($goodInfo['info_type'], [5, 6, 7], true))
            {
                if (empty($name2))
                {
                    return show(config('code.error'), '请求异常！Ta的真实姓名不能为空～');
                } else
                {
                    $questionData['name2'] = $name2;
                }
                if (empty($photo2))
                {
                    return show(config('code.error'), '请求异常！Ta的照片信息缺失～');
                } else
                {
                    $questionData['photo2'] = $photo2;
                }
            }
        } elseif ($goodInfo['type'] === 2)
        {   // 塔罗
            $cardsArr = $cards ? json_decode($cards, true) : [];
            if (count($cardsArr) !== $goodInfo['card_num'])
            {
                return show(config('code.error'), '咨询塔罗数据异常！');
            }
            $questionData['cards'] = $cards;
        } elseif ($goodInfo['type'] !== 6)//实物商品
        {   // $goodInfo['type'] = 5  骰子
            if (empty($question))
            {
                return show(config('code.error'), '咨询问题不能为空！');
            }
            if (mb_strlen($question) > 30)
            {
                return show(config('code.error'), '咨询问题最多30字！');
            }
            $divinationDataArr = $divinationData ? json_decode($divinationData, true) : [];
            if (!$divinationDataArr || !isset($divinationDataArr['planet'], $divinationDataArr['sign'], $divinationDataArr['house']))
            {
                return show(config('code.error'), '咨询骰子数据异常！');
            }

            $questionData['question'] = $question;
            $questionData['divination_data'] = $divinationData;
        }

        $supplementInfoData = $supplementInfo ? json_decode($supplementInfo, true) : [];

        $resSupplementInfoData = [];
        if (isset($goodInfo['extend'], $goodInfo['extend']['supplement_info']) && $goodInfo['extend'])
        {
            foreach ($goodInfo['extend']['supplement_info'] as $item)
            {
                if (!isset($supplementInfoData[$item['id']]) || empty(trim($supplementInfoData[$item['id']])))
                {   // 当前问题未回答
                    if ($item['content']['is_required'])
                    {
                        return show(config('code.error'), $item['content']['title'] . '【必' . ($item['type'] == 1 ? '选' : '填') . '】');
                    } else
                    {
                        continue;
                    }
                }

                $optionValue = trim($supplementInfoData[$item['id']]);

                if ((int)$item['type'] === 1)
                {   // 选择题
                    $optionData = array_column($item['content']['option'], null, 'id');
                    $op = [];
                    if ($item['content']['is_multi_choice'])
                    {   // 多选
                        $optionValue = explode(',', $optionValue);
                        foreach ($optionValue as $optionId)
                        {
                            if (isset($optionData[$optionId]))
                            {
                                $op[] = $optionData[$optionId];
                            } else
                            {
                                return show(config('code.error'), $item['content']['title'] . '答案数据异常');
                            }
                        }
                    } else
                    {
                        if (isset($optionData[$optionValue]))
                        {
                            $op = $optionData[$optionValue];
                        } else
                        {
                            return show(config('code.error'), $item['content']['title'] . '答案数据异常');
                        }
                    }
                    $resSupplementInfoData[$item['id']] = [
                        'title' => $item['content']['title'],
                        'type' => (int)$item['type'],
                        'is_multi_choice' => (int)$item['content']['is_multi_choice'],
                        'option' => $op,
                    ];
                } else
                {   // 填空提
                    if (mb_strlen($optionValue) > 60)
                    {
                        return show(config('code.error'), $item['content']['title'] . '答案数据异常');
                    }
                    $resSupplementInfoData[$item['id']] = [
                        'title' => $item['content']['title'],
                        'type' => (int)$item['type'],
                        'content' => $optionValue,
                    ];
                }
            }
        }
        $resSupplementInfoData = json_encode($resSupplementInfoData, JSON_UNESCAPED_UNICODE);
        $questionData = json_encode($questionData, JSON_UNESCAPED_UNICODE);

        if (Util::commentCheck($this->user['id'], [
            'question_data' => $questionData,
            'supplement_info' => $resSupplementInfoData,
        ]))
        {
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }

        if ($id)
        {   // 更新
            $oldQuestionData = $questionInfoModel->getPrivateAreaQuestionInfo($id, ['uid', 'hash', 'status']);
            if ($this->user['id'] !== $oldQuestionData['uid'] || $oldQuestionData['hash'] !== $sn || $oldQuestionData['status'] !== 0)
            {
                return show(config('code.error'), '服务异常，请稍后再试～');
            }

            $data = [
                'question_data' => $questionData,
                'supplement_info' => $resSupplementInfoData,
            ];

            // 提交数据入库
            $questionInfoModel->updateUserQuestionData($id, $data);
        } else
        {
            $data = [
                'uid' => $this->user['id'],
                'hash' => $sn,
                'status' => 0,
                'question_data' => $questionData,
                'supplement_info' => $resSupplementInfoData,
                'create_time' => $this->request->time(),
            ];
            // 提交数据入库
            $id = $questionInfoModel->insertGetId($data);
        }

        return show(config('code.success'), '提交成功', [
            'qid' => (int)$id
        ]);
    }

    /**
     * 用户咨询信息
     */
    public function questionInfo()
    {
        $qid = input('qid/d', 0);

        $questionInfoModel = new PrivateAreaQuestionInfo();

        $questionInfo = $questionInfoModel->getPrivateAreaQuestionInfo($qid);

        if (!$questionInfo || $questionInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常！咨询问题信息缺失～');
        }

        $goodInfo = (new PrivateAreaGoods())->getPrivateAreaGoodInfo($questionInfo['hash'], ['type', 'info_type', 'name']);

        $resData = $questionInfoModel->questionIndeResetShow($questionInfo, $goodInfo, $this->isAdmin);

        return show(config('code.success'), '提交成功', ['list' => $resData]);
    }

    /**
     * 获取解答结果
     */
    public function getQuestionAnswer()
    {
        $orderId = input('order_id/s', '');

        $questionInfoModel = new PrivateAreaQuestionInfo();
        $orderInfo = (new PrivateAreaOrders())->getInfoById($orderId, ['uid', 'status', 'qid']);

        if (!$orderInfo || $orderInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常，订单不存在～');
        }

//        if ($orderInfo['status'] != 4)
//        {
//            return show(config('code.error'), '服务异常，请稍后再试～');
//        }

        $answerData = $questionInfoModel->getPrivateAreaQuestionInfo($orderInfo['qid'], ['answer_content', 'status']);

        $answerDataArr = json_decode($answerData['answer_content'], true);
        if ($answerDataArr)
        {
            $aliOss = AliOss::getInstance();
            foreach ($answerDataArr as $key => $value)
            {
                $url = $aliOss->getAuth($value['url']);
                $url = str_replace('http://zhunle.oss-cn-beijing.aliyuncs.com', 'https://oss.goddessxzns.com', $url);
                $answerDataArr[$key]['url'] = $url;
            }
        }

        return show(config('code.success'), '请求成功', $answerDataArr);
    }
}
